package main

import (
	"bufio"
	"ccmouse/functional/fib"
	"fmt"
	"os"
)

func tryDefer() {
	fmt.Println(1)
	fmt.Println(2)
	defer fmt.Println(3)
	defer fmt.Println(4)
	// panic("123")
	return
	fmt.Println(5)
}

func writeFile(filename string) {
	file, err := os.OpenFile(filename,
		os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0666)
	if err != nil {
		// err handle
		if pathErr, ok := err.(*os.PathError); ok {
			fmt.Printf("op: %s, path: %s, err: %s",
				pathErr.Op, pathErr.Path, pathErr.Err)
			return
		} else {
			// re panic
			panic(err)
		}
	}
	defer func() { file.Close() }()

	g := fib.Fibonacci()
	writer := bufio.NewWriter(file)
	defer func() { writer.Flush() }()
	for i := 0; i < 20; i++ {
		fmt.Fprintf(writer, "%d\n", g())
	}
}

func main() {
	// tryDefer()
	const filename = "fib.txt"
	writeFile(filename)
}
